<!-- 人员类型页面 -->

<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew
        :title="title"
        :breadCrumb="breadCrumb"
        :isShowBtn="true"
        showBack
      >
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入文字"
          search-button
          @search="onSearch"
          @press-enter="onSearch"
          v-model="nameSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </template>
      <template #right>
        <a-button
          type="primary"
          @click="add"
          :style="{
            marginRight: '10px'
          }"
          >新增模板
        </a-button>
        <a-button type="outline" @click="remove(null)" status="danger"
          >批量删除</a-button
        >
        <!-- <a-button type="outline" @click="edit(1)">云端信息模板库 </a-button> -->
      </template>
    </ConditionBox>

    <TableTurn
      ref="tableRef"
      :tableData="searchData"
      style="margin-top: 20px"
      :args="args"
    >
      <a-table-column align="center" :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        title="人员信息模板名称"
        data-index="name"
        :width="200"
        align="center"
      ></a-table-column>
      <!-- <a-table-column
        :width="200"
        title="最新修改时间"
        data-index="isLegalPerson"
      >
      </a-table-column>
      <a-table-column
        :width="200"
        title="创建人"
        data-index="description"
      ></a-table-column>
      <a-table-column
        :width="200"
        title="创建时间"
        data-index="status"
      ></a-table-column> -->
      <a-table-column
        :width="200"
        title="描述"
        data-index="remark"
        align="center"
      ></a-table-column>

      <a-table-column
        align="center"
        :width="200"
        title="启用状态"
        data-index="enable"
      >
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="200"
        title="是否为默认模板"
        dataIndex="isShowDefault"
      >
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.isShowDefault"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column align="center" title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="20"
                @click="goPreview(record.id)"
                style="padding-bottom: 3px; color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?"
                position="left"
                @ok="remove(record)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
  <NoticeTemplate
    ref="templateRef"
    :data="currRecord.data"
    :business-type="businessType"
    :validateFun="validateName"
    :add="addData"
    :tab-code-list="businessType"
    :edit="EditData"
    :fn="tableRef"
    title="人员信息模板"
  ></NoticeTemplate>
  <PreviewForm :data="currRecord.data" v-model:visible="previewFormVisible">
  </PreviewForm>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router';
import { useSetupFormStore } from '@/store';
// import { GetControl } from '@/apis/management/base';
import {
  GetHumanTemplateList,
  PostHumanTemplate,
  PutHumanTemplate,
  GetHumanTemplateDetail,
  DelHumanTemplateList,
  PutHumanTemplateState,
  CheckHumanTemplateList,
  DelHumanTemplateDetails
} from '@/apis/management/human/baseSetting/humanSetting';
import { validateRules } from '@/utils/common';
import { cloneDeep } from 'lodash';
import { Message, Modal } from '@arco-design/web-vue';
import ContentCard from '@/components/ContentCard/index.vue';

const props = withDefaults(
  defineProps<{
    // clientName: string; // 客户名称
    dataList: any; // 状态列表
  }>(),
  {}
);

let tableRef = ref();
const router = useRouter();
const title = '人员信息模板';
let templateRef = ref();

const store = useSetupFormStore();
const breadCrumb: string[] = ['人事', '基础设置', '人员信息模板'];

const businessType = ref([
  'SER_FUNC751D0BFF5DF442209D437EE9A581693E',
  'baseComponent'
]);

// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

let originData = ref(); // 储存原始数据
let nameSearch = ref();
// 获取表数据
const searchData = async (page: any) => {
  try {
    const res: any = await GetHumanTemplateList({
      ...page,
      name: nameSearch.value
    });
    // for (let i = 0; res.content.length > i; i++) {
    //   if (res.content[i].isLegalPerson == 2) {
    //     res.content[i].isLegalPerson = '否';
    //   } else {
    //     res.content[i].isLegalPerson = '是';
    //   }
    //   if (res.content[i].status == 2) {
    //     res.content[i].status = '禁用';
    //   } else {
    //     res.content[i].status = '启用';
    //   }
    // }
    originData.value = cloneDeep(res.content);
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log('查询错:', error);
  }
};

// 搜索框
const onSearch = () => {
  refresh({
    pageNumber: 0,
    pageSize: -1
  });
};

// 点击编辑
const edit = (record: any) => {
  currRecord.list = record;
  templateRef.value.fullScreen();
};

// 修改模板默认状态
const stateChange = async (record: any) => {
  try {
    // 获取更改状态之前的模板数据，并判断状态是否和当前的一样，如果一样则不能改成默认模板
    const temp = originData.value.find((item: any) => item.id === record.id);
    if (temp.isShowDefault === 1) Message.error('必须拥有一个默认模板！');
    else if (temp.enable !== 1)
      Message.error('不能将未启用的模板当作默认模板!');
    else
      await PutHumanTemplateState({
        id: record.id
      });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除(确定弹框没有UI)
const remove = async (record: any | null) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find(
                  (item: any) => item.isShowDefault === 1
                )
              ) {
                Message.error('默认模板不能删除！');
              } else if (
                selectedListData.value.find(
                  (item: any) => item.isSysDefault === 1
                )
              ) {
                Message.error('系统默认模板不能删除!');
              } else {
                await DelHumanTemplateDetails({
                  level: 1,
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                refresh();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.isShowDefault === 1) Message.error('默认模板不能删除！');
      else if (record.isSysDefault === 1) {
        Message.error('系统默认模板不能删除!');
      } else {
        await DelHumanTemplateDetails({
          level: 1,
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        refresh();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
// 储存当前数据
const currRecord: any = reactive({ data: {} });

// 点击新增模板按钮
const add = () => {
  currRecord.data = {
    name: '',
    enable: 1,
    remark: ''
  };
  templateRef.value.fullScreen();
};

let previewFormVisible = ref(false);

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currRecord.data.name && currRecord.data.id) {
      //
    } else {
      const data = {
        name
      };
      const res = await validateRules(CheckHumanTemplateList, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 预览
const goPreview = async (id: number) => {
  try {
    const res: any = await GetHumanTemplateDetail({ id });
    currRecord.data.name = res.name;
    currRecord.data.details = res.collectionModel;
    previewFormVisible.value = true;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 编辑 初始化控件数据
const goEdit = async (id: number, name?: string) => {
  const record: any = cloneDeep(await GetHumanTemplateDetail({ id }));
  record.seconds = record.collectionModel;
  delete record.collectionModel;
  if (name) {
    record.name = name;
    delete record.id;
  }
  record.seconds.forEach((ele: any) => {
    if (name) delete ele.id;
    ele.componentList = ele.controlModel;
    delete ele.componentModel;
    ele.componentList.forEach((item: any) => {
      const { ctlCnName, ctlEnName, ctlComponentType, ctlCode, ctlFieldName } =
        item;
      item.uuid = ctlCode;
      item.componentName = ctlCnName;
      item.componentType = ctlComponentType;
      item.code = ctlCode;
      item.fieldName = ctlFieldName;
      item.enName = ctlEnName;
      if (name) delete item.id;
      item.props = item.props?.length ? JSON.parse(item.props) : void 0;
      if (item?.controlChildren?.length) {
        item.childrenCtl = item?.controlChildren;
        item?.childrenCtl?.forEach((ctlChi) => {
          ctlChi.uuid = ctlChi.ctlCode;
          ctlChi.props = ctlChi.props?.length
            ? JSON.parse(ctlChi.props)
            : void 0;
        });
      }
    });
  });
  currRecord.data = cloneDeep(record);
  templateRef.value.fullScreen();
};
// 新增 模板新增函数
const addData = async (data: any, componentList: any) => {
  try {
    // 第一层，返回templateId赋值给第二层子集
    const { id: templateId } = await PostHumanTemplate({
      level: 1, // 默认传1
      template: {
        enable: data.enable,
        name: data.name,
        remark: data.remark,
        ownerFuncType: 3 // 人员默认传3
      }
    });
    let component = cloneDeep(componentList);
    // 用createdAt进行判断用户是否是复制再编辑模板
    if (component[0]?.createdAt) {
      component = [
        {
          componentList: component
        }
      ];
    }
    for (let [index, item] of component.entries()) {
      for (let item2 of item.componentList) {
        const collection = {
          cnName: item2.cnName,
          enName: item2.enName,
          subCode: item2.subCode,
          orderNo: item2.sort || index,
          templateId
          // pid: item2.pid || 0
        };
        const { id: collectionId } = await PostHumanTemplate({
          level: 2, // 第二层默认传2
          collection
        });
        // 将返回的collectionId赋值给每一个控件
        // item2.componentList.forEach((item2: any, index3: number) => {
        //   item2.collectionId = collectionId;
        // });
        const control = item2.componentList.map((item2: any) => {
          item2.collectionId = collectionId;
          item2.props = JSON.stringify(item2.props);
          let data;
          if (item2.subsetControlRel) {
            data = {
              ...item2,
              ...item2.subsetControlRel
            };
          } else {
            data = {
              ...item2
            };
          }
          if (data.subsetControlRel) delete data.subsetControlRel;
          data.controlChildren = data.childrenCtl;
          data?.controlChildren?.forEach((ctlChi) => {
            ctlChi.props = JSON.stringify(data.props);
            ctlChi.id = void 0;
            ctlChi.ctlComponentType = ctlChi.componentType;
            ctlChi.ctlFieldName = ctlChi.fieldName;
            ctlChi.ctlEnable = ctlChi.enable;
            ctlChi.ctlIsDefault = ctlChi.isDefault;
            ctlChi.ctlRequired = ctlChi.required;
          });
          return data;
        });
        await PostHumanTemplate({
          level: 3, // 第三层传3
          control
        });
      }
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};
// 新增 模板编辑函数
const EditData = async (data: any, componentList: any) => {
  try {
    const templateId = data.id;
    // 第一层，返回templateId赋值给第二层子集
    await PutHumanTemplate({
      level: 1, // 默认传1
      template: {
        ...data,
        // ownerId: id,
        ownerFuncType: 3 // 人员默认传3
      }
    });

    // 删除子集
    if (store.getCollectionsIds.length > 0) {
      await DelHumanTemplateDetails({
        level: 2,
        ids: store.getCollectionsIds
      });
      store.delCollectionsIds = [];
    }

    // // 删除控件
    if (store.getControlIds.length > 0) {
      await DelHumanTemplateDetails({
        level: 3,
        ids: store.getControlIds
      });
      store.delControlIds = [];
    }

    const component = cloneDeep(componentList);
    // // 循环修改值的结构
    for (let [index, item] of component.entries()) {
      const collection: any = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
        // pid: item2.pid || 0
      };
      let collectionId = 0;
      if (item.id) {
        collection.id = item.id;
        await PutHumanTemplate({
          level: 2, // 第二层默认传2
          collection
        });
        collectionId = item.id;
      } else {
        collectionId = (await PostHumanTemplate({
          level: 2, // 第二层默认传2
          collection
        })) as number;
      }
      for (let item2 of item.componentList) {
        item2.collectionId = collectionId;
        item2.props = JSON.stringify(item2.props);
        item2?.controlChildren?.forEach((ctlChi) => {
          ctlChi.props = JSON.stringify(data.props);
          // ctlChi.id = void 0;
        });
      }
      await PutHumanTemplate({
        level: 3, // 第三层传3
        control: item.componentList
      });
    }

    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};
let copyVisible = ref(false);
let currId = ref(0);
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

// // 复制
const copyEmit = async (formData: any) => {
  try {
    const record: any = await GetHumanTemplateDetail({ id: currId.value });
    delete record.id;
    delete record.createdAt;
    record.required = 2;
    record.name = formData.name;
    const template = cloneDeep(record);
    delete template.collectionModel;
    const { id: templateId } = await PostHumanTemplate({
      level: 1, // 默认传1
      template: {
        ...template,
        ownerType: 3, // 人员默认传3
        isShowDefault: 2 // 复制的时候默认为不是默认模板
      }
    });
    const component = cloneDeep(record.collectionModel);
    for (let [index, item] of component.entries()) {
      delete item.id;
      const collection = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
      };
      const { id: collectionId } = await PostHumanTemplate({
        level: 2, // 第二层默认传2
        collection
      });
      // 将返回的collectionId赋值给每一个控件
      item.controlModel.forEach((item2: any, index3: number) => {
        item2.collectionId = collectionId;
        delete item2.id;
      });
      await PostHumanTemplate({
        level: 3, // 第三层传3
        control: item.controlModel
      });
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    refresh();
  } catch (error) {
    console.log(error);
  }
};
// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};

const refresh = (pageData?: any) => {
  tableRef.value.loadData();
};
</script>

<style scoped lang="less">
.base-setting {
  &-warp {
    display: flex;
    flex: 1;
    flex-wrap: wrap;
  }
  .header {
    display: flex;
    justify-content: space-between;
  }
}
.optionalSe {
  display: inline;
  cursor: pointer;
}
.newOrganization {
  float: right;
  margin: 20px 20px 0 0;
  color: #409eff;
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 5px;
  justify-content: space-around;
}
.operation {
  display: flex;
  justify-content: end;
  p {
    margin: 0 10px;
    color: #3d7eff;
    cursor: pointer;
  }
  p:last-child {
    color: red;
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
